package net.njcp.mybatis.frame.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName QueryUtil
 * @Description: TODO
 * @Author 柳拓
 * @Date 2019/8/13
 * @Version V1.0
 **/
public class QueryUtil {

    //通过表明获取别名
    public static String getAliasTableName(String tableName){
        StringBuilder aliasNameBuilder = new StringBuilder();
        Arrays.asList(tableName.split("_")).stream().forEach(s -> {aliasNameBuilder.append(s.substring(0, 1));});
        return aliasNameBuilder.toString();
    }

    //通过Class名称获取表名
    public static String getTableName(Class tClass) {
        //通过Class名称获取对象名
        String objectName = ReflectUtil.toLowerCaseFirstOne(tClass.getSimpleName());
        //获取表名
        String tableName = getTableName(objectName);
        return tableName;
    }

    //根据对象名称获取表明
    public static String getTableName(String ObjectName) {
        return MatchesUtil.switchParam(ObjectName);
    }

    //根据表名称、结果字符串获取查询字段集合
    public static List<String> getFieldsList(String tableName, String resultFields) {
        List<String> fieldsList = new ArrayList<>();
        if (resultFields != null && !resultFields.isEmpty()) {
            String fields[] = resultFields.split(",");
            for (String field : fields) {
                fieldsList.add(propertyToField(tableName,field));
            }
        }
        return fieldsList;
    }

    //根据表名称、结果字符串获取查询字段xx.xx
    public static String propertyToField(String tableName, String field){
        StringBuilder fieldsStatement = new StringBuilder();
        //若果包括中括号,如同SUM(PRICE) AS PRICE
        if (field.indexOf("(") > -1) {
            //将括号内的字符串转成字段
            String[] field1 = field.split("\\(");
            String[] field2 = field1[1].split("\\)");
            fieldsStatement.append(field1[0]);
            fieldsStatement.append("(");
            if(field2[0].equals("*")){
                fieldsStatement.append("*");
            }else{
                fieldsStatement.append(tableName + ".");
                fieldsStatement.append(MatchesUtil.switchParam(field2[0]));
            }
            fieldsStatement.append(")");
            fieldsStatement.append(field2[1]);
        } else {
            fieldsStatement.append(tableName + ".");
            fieldsStatement.append(MatchesUtil.switchParam(field));
        }
        return fieldsStatement.toString();
    }

}
